const fsTool = require("../fs/fsapi");
const path = require("path");
const responseEntity = require('../tools/responseEntity')
const http = require('http')
const { secretKey } = require('../tools/business')
const jwt = require('jsonwebtoken')
const DB = require('../tools/mongodb')
const { v4: uuidv4 } = require('uuid');
const nick_controller = require('./nick')

const Util = {
  async userIsAlerady (loginName) {
    const loginData = await DB.find('users', {
      loginName
    })
    return loginData
  }
}

const api = {
  async login (req, res) {
    // 错误拦截
    const loginData = await Util.userIsAlerady(req.body.loginName)
    if (!loginData.length || (req.body.loginName !== loginData[0].loginName && req.body.password !== loginData[0].password)) {
      return responseEntity.setEneity({
        res,
        status: '400',
        message: '登录失败'
      })
    }
    const menusData = await DB.find('menus')
    const tokenStr = jwt.sign({ username: req.body.loginName }, secretKey, { expiresIn: '2h' })
    return responseEntity.setEneity({
      res,
      data: {
        user: loginData[0],
        menus: menusData,
        token: tokenStr
      }
    })
  },
  async signup (req, res) {
    const loginData = await Util.userIsAlerady(req.body.loginName)
    if (loginData.length) {
      return responseEntity.setEneity({
        res,
        status: '400',
        message: '登录用户名重复'
      })
    }
    if (await nick_controller.isAlerady(req.body.userName)) {
      return responseEntity.setEneity({
        res,
        status: '400',
        message: '用户昵称重复'
      })
    }

    nick_controller.writeNickTag(req.body.userName)

    DB.insertOne('users', Object.assign(req.body, {
      userId: uuidv4,
      roleId: ''
    }))
    return responseEntity.setEneity({
      res,
      data: req.body
    })

  },
  async getMenus (req, res) {
    const menusData = await DB.find('menus')
    return responseEntity.setEneity({
      res,
      data: menusData
    })
  }
}
module.exports = api;